#region Using directives
using System;
#endregion

namespace SharpWind.Helpers
{
	public class Timer
	{
		#region Fields

		private long ticksPerSecond;

		private long lastTime;

		private float runningTime;

		private float elapsedTime;

		private bool isStopped;

		#endregion

		#region Constructor

		public Timer()
		{
			Win32.QueryPerformanceFrequency( ref this.ticksPerSecond );

			this.isStopped = true;
		}

		#endregion

		#region Methods

		public void Start()
		{
			if( this.isStopped )
			{
				Win32.QueryPerformanceCounter( ref this.lastTime );

				this.isStopped = false;
			}
		}

		public void Stop()
		{
			if( !this.isStopped )
			{
				this.runningTime += (float)( CurrentTime - this.lastTime ) / (float)this.ticksPerSecond;

				this.isStopped = true;
			}
		}

		internal void Update()
		{
			if( !this.isStopped )
			{
				long currentTime = CurrentTime;

				this.elapsedTime = (float)( currentTime - this.lastTime ) / (float)this.ticksPerSecond;
				this.runningTime += this.elapsedTime;
				this.lastTime = currentTime;
			}
		}

		#endregion

		#region Properties
		
		public bool IsStopped
		{
			get
			{
				return this.isStopped;
			}
		}

		public float ElapsedTime
		{
			get
			{
				return this.elapsedTime;
			}
		}

		public float RunningTime
		{
			get
			{
				if( this.isStopped )
				{
					return 0;
				}

				return this.runningTime;
			}
		}

		internal long TicksPerSecond
		{
			get
			{
				return this.ticksPerSecond;
			}
		}

		internal long CurrentTime
		{
			get
			{
				long currentTime = 0;
				Win32.QueryPerformanceCounter( ref currentTime );

				return currentTime;
			}
		}

		#endregion
	}
}